# -*- coding: utf-8 -*-

import copy
import json
import time

import common
from common import log

class MergeError(Exception):
    pass

class MergerBase(object):
    def __init__(self):
        pass
    def reload(self):
        pass
    def merge(self, old_doc, new_doc):
        pass

class MergeManager(object):
    def __init__(self, data_saver):
        from merger.merger_meta import MetaMerger
        from merger.merger_default import DefaultMerger
        self.merger_map = {
            'meta': MetaMerger(),
            'default': DefaultMerger()
            # Other mergers [merger-name: merger-instance]
        }

    def reload(self):
        for merger in self.merger_map.itervalues():
            merger.reload()
        log.info('MergeManager loading finished!')

    def merge(self, task):
        '''
        新旧记录merge

        总体合并逻辑: 
            先把旧数据作为current_entity_data, 将task.merger_names中指定的merger依次作用在current_entity_data上
        '''

        for merger_name in task.merger_names:
            try:
                merger_to_use = self.merger_map[merger_name]
            except KeyError, e:
                log.error('MergeManager: merger_name[%s] not found!' % validator_name)
                raise
            log.debug('MergeManager: merger[%s] starting' % (merger_name))
            merger_to_use.merge(task)
            #log.debug('MergeManager: merger[%s] finished, current_entity_data[%s]' % (merger_name, task.current_entity_data))
            log.debug('MergeManager: merger[%s] finished' % (merger_name))
